package com.kung.qvs.ui.main.fragment;

import android.content.DialogInterface;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.Navigation;

import com.afollestad.materialdialogs.MaterialDialog;
import com.kung.qvs.BR;
import com.kung.qvs.R;
import com.kung.qvs.app.AppViewModelFactory;
import com.kung.qvs.databinding.FragMainBinding;
import com.kung.qvs.entity.PrintDataBean;
import com.kung.qvs.entity.WorkerBean;
import com.kung.qvs.entity.database.SqlManager;
import com.kung.qvs.ui.main.HomeActivity;
import com.kung.qvs.ui.main.KungViewModel;
import com.kung.qvs.ui.widget.ConformDialog;
import com.kung.qvs.utils.CommonUtils;
import com.kung.qvs.utils.Constants;
import com.kung.qvs.utils.QrCodeUtils;
import com.lcodecore.tkrefreshlayout.utils.LogUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class MainFrag extends BaseFragment<FragMainBinding, MainViewModel> {

    private String TAG = MainFrag.class.getSimpleName();
    private KungViewModel kungViewModel;
    private HomeActivity homeActivity;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  //设置日期格式
    private Bitmap qrBitmap;

    private MaterialDialog mSimpleDialog;

    private boolean isResetZero = true;    //是否清零,清零过，可以再次自动保存
    private int receiverNum = 0;    //接收次数
    private static int steadyNum = 20;   //稳定接收次数

    private TextWatcher textWatcher;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.frag_main;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MainViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(getActivity(), factory).get(MainViewModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        homeActivity = (HomeActivity) getActivity();
        //软盘弹出，页面不做变化
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

        kungViewModel = new ViewModelProvider(getActivity()).get(KungViewModel.class);
        kungViewModel.setmIsHomeFrag(true);

//        int ss = Integer.parseInt("1");

        kungViewModel.getmIsBleBalanceConnect().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    binding.tvScalsState.setText("已连接");
                    binding.tvScalsState.setTextColor(getResources().getColor(R.color.colorPrimary));
                    binding.layoutBluetooth.setBackground(getResources().getDrawable(R.drawable.shape_btn_rect_corner_green));
                    binding.ivScale.setImageResource(R.mipmap.ic_bluetooth_connect);
                } else {
                    binding.tvScalsState.setText("未连接");
                    binding.tvScalsState.setTextColor(getResources().getColor(R.color.btnColorRed));
                    binding.layoutBluetooth.setBackground(getResources().getDrawable(R.drawable.shape_btn_rect_corner_red));
                    binding.ivScale.setImageResource(R.mipmap.ic_bluetooth_disconnect_red);
                }
            }
        });

        kungViewModel.getmIsBlePrinterConnect().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    binding.tvPrinterState.setText("已连接");
                    binding.tvPrinterState.setTextColor(getResources().getColor(R.color.colorPrimary));
                    binding.layoutPrinter.setBackground(getResources().getDrawable(R.drawable.shape_btn_rect_corner_green));
                    binding.ivPrinter.setImageResource(R.mipmap.ic_printer_on);
                    Log.e("MainFrag","888888888888888888888888888");
                } else {
                    binding.tvPrinterState.setText("未连接");
                    binding.tvPrinterState.setTextColor(getResources().getColor(R.color.btnColorRed));
                    binding.layoutPrinter.setBackground(getResources().getDrawable(R.drawable.shape_btn_rect_corner_red));
                    binding.ivPrinter.setImageResource(R.mipmap.ic_printer_off);
                }
            }
        });

        kungViewModel.getMWeight().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String tempWeight) {
                try {
                    if (Constants.WEIGHT_UNIT_KG.equals(viewModel.mUnit.get())) {
                        double weight = Double.parseDouble(tempWeight) - Double.parseDouble(viewModel.mTareWeight.get());
                        viewModel.mWeight.set(String.format("%.2f", weight));

                        if (viewModel.mSelectedProductBean.get() != null && !StringUtils.isEmpty(viewModel.mSelectedProductBean.get().getWeight())) {
                            double amount = weight / Double.parseDouble(viewModel.mSelectedProductBean.get().getWeight());
                            //四舍五入
                            viewModel.mAmount.set(Math.round(amount) + "");
                        } else {
                            viewModel.mAmount.set("0");
                        }

                    } else {
                        //斤
                        double weight = Double.parseDouble(tempWeight) * 2f;
                        viewModel.mWeight.set(String.format("%.2f", weight));
                    }

                    if (Double.parseDouble(viewModel.mWeight.get()) <= 0) {
                        isResetZero = true;
                        Log.i("MainFrag", "isResetZero = true   2");
                    }

                    viewModel.mTime.set(df.format(new Date()));

                    //稳定后，自动保存
                    if (viewModel.lastWeight.get().equals(viewModel.mWeight.get())) {
                        //稳定，则增加次数
                        receiverNum++;
                    } else {
                        //不同，重新计算
                        viewModel.lastWeight.set(viewModel.mWeight.get());
                        receiverNum = 0;
                    }
                    if (receiverNum >= steadyNum && isResetZero && viewModel.isUploadAllowed) {
                        //稳定后，自动保存
//                        ToastUtils.showShort("稳定后，自动保存");
                        if (!StringUtils.isTrimEmpty(viewModel.mWeight.get()) && Double.parseDouble(viewModel.mWeight.get()) > 0) {
                            viewModel.doSaveTrashRecord();
                            viewModel.isUploadAllowed = false;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    viewModel.mWeight.set("0.00");
                }
            }
        });

        kungViewModel.getmIsHasHardWareCode().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean && !viewModel.hasTrashTypes()) {
//                    viewModel.initGarbageTypes();
                }
            }
        });

        kungViewModel.getmSelectWorker().observe(this, new Observer<WorkerBean>() {
            @Override
            public void onChanged(WorkerBean workerBean) {
                if (workerBean == null) {
                    viewModel.mWorkerBean.set(null);
                    return;
                }

                if (workerBean != null && viewModel.mWorkerBean.get() != null) {
                    if (workerBean.getUserName().equals(viewModel.mWorkerBean.get().getUserName())) {
                        return;
                    }
                }
                viewModel.mWorkerBean.set(workerBean);
                receiverNum = 0;
                isResetZero = true;
                viewModel.isUploadAllowed = true;
            }
        });

        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 文本变化之前的回调
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 文本变化时的回调，执行搜索操作
                String keyword = s.toString();
//                if (keyword.length() == 0) {
//                    return;
//                }
                viewModel.funGetProducts(keyword);
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 文本变化之后的回调
            }
        };

        binding.etSearchKey.addTextChangedListener(textWatcher);

//        qrBitmap = QrCodeUtils.createQRCodeBitmap("welcome", 800, 800,"UTF-8","H", "1", Color.BLACK, Color.WHITE);
//        binding.ivQr.setImageBitmap(qrBitmap);

        kungViewModel.getmSearchWorkerCode().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (StringUtils.isEmpty(s)) {
                    return;
                }
                WorkerBean workerBean = SqlManager.queryProductWorkerBeanByUserName(s);
                kungViewModel.setmSearchWorkerCode("");
                if (workerBean == null) {
                    kungViewModel.setmSelectWorker(null);
                    viewModel.mWorkerBean.set(null);
                    ToastUtils.showShort("未找到工人信息");
                    return;
                }
                //如果是同一个工人，不做处理
                if (kungViewModel.getmSelectWorker().getValue() != null && kungViewModel.getmSelectWorker().getValue().getUserName().equals(workerBean.getUserName())) {
                    ToastUtils.showShort("已选择该工人");
                    return;
                }
                kungViewModel.setmSelectWorker(workerBean);
            }
        });

        kungViewModel.getmScanProductCode().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (StringUtils.isEmpty(s)) {
                    //没扫到，情况选择的产品
                    viewModel.setGarbageTypeSelectState(null, false);
                    return;
                }
                viewModel.queryLocalProduct(s);
            }
        });

        viewModel.mPrintSelected.set(kungViewModel.getmSelectPrintCount().getValue());

        //加载产品列表
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                viewModel.reLoadSomeData2();
                viewModel.initProductTypes();
            }
        }, 800);
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.etSearchKey.addTextChangedListener(textWatcher);
        //延时1秒执行
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                viewModel.reLoadSomeData();
            }
        }, 800);
    }

    @Override
    public void onPause() {
        super.onPause();
        binding.etSearchKey.removeTextChangedListener(textWatcher);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.eventBleBalance.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
//                if (kungViewModel.getmIsBleBalanceConnect().getValue()) {
//                    homeActivity.doDisconnectBleBalance();
//                } else {
//                    homeActivity.doConnectBleBalance();
//                }
            }
        });

        viewModel.uc.eventBlePrinter.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
//                if (kungViewModel.getmIsBlePrinterConnect().getValue()) {
//                    homeActivity.doDisconnectBlePrinter();
//                } else {
//                    homeActivity.doConnectBlePrinter();
//                }
            }
        });

        viewModel.uc.eventCommondCumulative.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                ConformDialog.Builder builder = new ConformDialog.Builder(getActivity());
                builder.setMessage("是否保存称重并打印?", "");
                builder.setTitle("保存打印");
                builder.setPositiveButton("保存",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog2,
                                                int which) {
                                dialog2.dismiss();
                                viewModel.doSaveTrashRecord();
                            }
                        });

                builder.setNegativeButton("取消",
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog2,
                                                int which) {
                                dialog2.dismiss();
                            }
                        });
                builder.create().show();
            }
        });

        viewModel.uc.eventPrintCommond.observe(this, new Observer<PrintDataBean>() {
            @Override
            public void onChanged(PrintDataBean trashDataBean) {
                homeActivity.doPrintContent(trashDataBean, "");
            }
        });

        viewModel.uc.eventToSettingPage.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                Bundle mBundle = new Bundle();
                Navigation.findNavController(getView()).navigate(R.id.settingFrag, mBundle);
            }
        });

        viewModel.uc.eventToCollectRecordPage.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                Bundle mBundle = new Bundle();
                Navigation.findNavController(getView()).navigate(R.id.collectTrashRecordFrag, mBundle);
            }
        });

        viewModel.uc.eventCommondQP.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                homeActivity.doPrintContent(null, "");
            }
        });

        viewModel.uc.eventChangeQrCode.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
//                qrBitmap = QrCodeUtils.createQRCodeBitmap(s, 800, 800,"UTF-8","H", "1", Color.BLACK, Color.WHITE);
//                binding.ivQr.setImageBitmap(qrBitmap);
            }
        });

        viewModel.uc.eventSelectWorker.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                Bundle mBundle = new Bundle();
                mBundle.putBoolean("isSelect", true);
                Navigation.findNavController(getView()).navigate(R.id.fragWorkers, mBundle);
            }
        });

        viewModel.uc.eventToInputTare.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                mSimpleDialog = new MaterialDialog.Builder(getActivity())
                        .title("皮重")
                        //限制输入的长度
                        .inputRangeRes(1, 6, R.color.textColorGreen)
                        //限制输入类型
                        .inputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL)
                        .input("请输入皮重", null, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                //判断是否为数字
                                if (!CommonUtils.isNumeric(String.valueOf(input))) {
                                    return;
                                }
                                viewModel.mTareWeight.set(String.valueOf(input));
                                viewModel.localSetTare();
                                receiverNum = 0;
                                isResetZero = true;
                                viewModel.isUploadAllowed = true;
                            }
                        })
                        .positiveText("确定")
                        .negativeText("取消")
                        .show();
            }
        });

        //输入公司名称
        viewModel.uc.eventToInputCompany.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                mSimpleDialog = new MaterialDialog.Builder(getActivity())
                        .title("公司名称")
                        //限制输入的长度
                        .inputRangeRes(1, 20, R.color.textColorGreen)
                        //限制输入类型
                        .input("请输入标签上公司名称", null, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                viewModel.mCompanyTitle.set(String.valueOf(input));
                                viewModel.localSetCompanyTitle();
                                receiverNum = 0;
                                isResetZero = true;
                                viewModel.isUploadAllowed = true;
                            }
                        })
                        .positiveText("确定")
                        .negativeText("取消")
                        .show();
            }
        });

        viewModel.uc.eventPlaySound.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                viewModel.mWorkerBean.set(null);
                viewModel.isUploadAllowed = true;
                homeActivity.funPlayAudioRecSuccess();
                isResetZero = false;
                //延时200ms执行下面操作
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//
//                    }
//                }, 200);
                kungViewModel.setmSelectWorker(null);
                //打印日志
                Log.i("MainFrag", "eventPlaySound");
            }
        });

        viewModel.uc.eventPlaySoundNoWorker.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                Log.i("MainFrag", "eventPlaySoundNoWorker");
                isResetZero = false;
                homeActivity.funPlayAudioRecNoWorker();
            }
        });

        viewModel.uc.eventToUploadDetail.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                Bundle mBundle = new Bundle();
                Navigation.findNavController(getView()).navigate(R.id.statisticTotalFrag, mBundle);
            }
        });

        viewModel.uc.eventSelectProductType.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                receiverNum = 0;
                isResetZero = true;
                viewModel.isUploadAllowed = true;
            }
        });

        viewModel.uc.eventChangePrintCount.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                kungViewModel.setmSelectPrintCount(integer);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        homeActivity = null;
    }
}
